import {SetStorage, GetRequestPage, GetStorage, API_NICKNAME} from "./common.js";

/**
 * @since 2025-03-04 初始化页面
 * chrome-extension://eabdmadddbkbdlmalneligkmanclfcam/html/popup.html
 */
$(document).ready(() => {
  InitPage();
});

/**
 * @since 2025-03-04 初始化页面
 */
async function InitPage() {
  let requestPage = await GetRequestPage();

  $('#request_page_start').val(requestPage.start);
  $('#request_page_now').html(requestPage.now);
  $('#request_page_end').val(requestPage.end);

  /**
   * @since 2025-03-04 获取公众号名称
   */
  let param = await GetStorage("wx_request_param");
  if (param === undefined) return ;

  let fakeid = param.fakeid;
  $('#fakeid').val(fakeid);


  let data = {
    "query": [
      {
        "msg": "微信公众号查询",
        "db": "db_carnoc",
        "table": "wx_account_list",
        "query": "rules_2d2f8a57db21a3f5e790242281ea5f7a",
        "where": {
          "fakeid": [
            "=",
            [
              fakeid
            ]
          ]
        },
        "page": 1,
        "pagesize": 1
      }
    ]
  };

  var settings = {
    "url": "https://service.carnoc.com/api/web/index.php/carnoc/db-query/index",
    "method": "POST",
    "timeout": 0,
    "headers": {
      "Content-Type": "application/json",
      "Accept": "*/*",
    },
    "data": JSON.stringify(data),
  };

  $.ajax(settings).done(function (response) {
    console.log(response);
    let nickname = response["list"][0]["data"][0]["nickname"];
    if(!nickname) return false;
    $('#nickname').val(nickname);
  });
}

/**
 * @since 2025-03-04 监听确认按钮
 */
$('#confirmBtn').click(() => {
  let start = parseInt($('#request_page_start').val());
  let end = parseInt($('#request_page_end').val());
  let nickname = $("#nickname").val();

  /**
   * @since 2025-03-04 验证end>=start
   */
  if (end >= start) {
    let requestPage = {
      start: start,
      now: start,
      end: end,
      nickname: nickname
    };
    SetStorage("request_page", requestPage);
    window.close();
  } else {
    alert('请输入有效的页码');
  }
});